import { login } from '../controller/user.js'
import { set } from '../db/redis.js'
import { ErrorModel, SuccessModel } from '../model/res-model.js'

const handleUserRouter = async (req, res) => {
	// 设置返回格式 JSON
	res.setHeader('Content-type', 'application/json')
	const method = req.method

	// 登录
	if (method === 'POST' && req.path === '/api/user/login') {
		const { username, password } = req.body
		const userData = await login(username, password)
		if (userData.username) {
			//操作 cookie
			/* res.setHeader(
				'Set-Cookie',
				'username=' +
					userData.username +
					';path=/;httpOnly;expires=' +
					getCookieExpires()
			) */

			req.session.username = userData.username
			req.session.realname = userData.realname

			// 同步到 redis 中
			set(req.sessionId, req.session)

			return new SuccessModel()
		}
		return new ErrorModel('登录失败')
	}

	/* // 登录验证的测试
	if (method === 'GET' && req.path === '/api/user/login-test') {
		if (req.session.username) {
			return new SuccessModel(req.session)
		}
		return new ErrorModel('尚未登录')
	} */
}

export default handleUserRouter
